﻿using Newtonsoft.Json;
using Production.CommonLib.Constants;
using Production.CommonLib.Models;
using Swimj.CommonLib.Base;
using Swimj.Core.Extensions;
using System.Net.Http.Json;

namespace Production.RazorLib.Services
{
    public class ProductionPlanService : IProductionPlanService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        public ProductionPlanService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }
    
        public async Task<PaginatedResult<ProductionPlanInfoResponseDto>?> QueryProductionPlansByPage(ProductionPlanSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("productionApi");
                var response = await httpClient.GetAsync(model.ToQueryString(ApiRoutes.ProductionPlan.QueryProductionPlans));
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<PaginatedResult<ProductionPlanInfoResponseDto>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<ProductionPlanInfoResponseDto>?> CreateProductionPlan(ProductionPlanEditRequestDto editRequestDto)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("productionApi");
                var response =
                    await httpClient.PostAsJsonAsync($"/{ApiRoutes.ProductionPlan.CreateProductionPlan}", editRequestDto);
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<ProductionPlanInfoResponseDto>>(resultJson);
                    }
                }

                return new Result<ProductionPlanInfoResponseDto>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
}